import React, { useRef, useState, useEffect } from 'react';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';

const ImageCropper = () => {
  // 图片相关状态
  const [imageSrc, setImageSrc] = useState(null);
  const [croppedImage, setCroppedImage] = useState(null);
  
  // DOM 引用
  const imageRef = useRef(null);
  const cropperRef = useRef(null);
  
  // 初始化裁剪器
  useEffect(() => {
    if (imageSrc && imageRef.current) {
      // 销毁已存在的裁剪器实例
      if (cropperRef.current) {
        cropperRef.current.destroy();
      }
      
      // 创建新的裁剪器实例
      cropperRef.current = new Cropper(imageRef.current, {
        aspectRatio: 1, // 裁剪框宽高比 (1:1 正方形)
        viewMode: 1,    // 限制裁剪框在图片内
        dragMode: 'move', // 拖动模式
        scalable: true,  // 允许缩放
        zoomable: true,  // 允许放大
        movable: true,   // 允许移动
        cropBoxResizable: true, // 允许调整裁剪框大小
        background: false, // 关闭背景网格
      });
    }
    
    // 组件卸载时销毁裁剪器
    return () => {
      if (cropperRef.current) {
        cropperRef.current.destroy();
      }
    };
  }, [imageSrc]);
  
  // 处理图片上传
  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    // 将文件转换为 DataURL
    const reader = new FileReader();
    reader.onload = (event) => {
      setImageSrc(event.target.result);
      setCroppedImage(null); // 重置裁剪结果
    };
    reader.readAsDataURL(file);
  };
  
  // 执行裁剪
  const handleCrop = () => {
    if (!cropperRef.current) return;
    
    // 获取裁剪后的图片数据
    const canvas = cropperRef.current.getCroppedCanvas({
      width: 200,  // 裁剪后图片宽度
      height: 200, // 裁剪后图片高度
      imageSmoothingQuality: 'high' // 高质量
    });
    
    // 转换为图片 URL
    const croppedUrl = canvas.toDataURL('image/png');
    setCroppedImage(croppedUrl);
  };
  
  // 下载裁剪后的图片
  const handleDownload = () => {
    if (!croppedImage) return;
    
    const link = document.createElement('a');
    link.href = croppedImage;
    link.download = 'cropped-image.png';
    link.click();
  };
  
  return (
    <div style={{ maxWidth: '800px', padding: '0 16px' }}>
      {/* 上传图片 */}
      <div style={{ marginBottom: '20px' }}>
        <input 
          type="file" 
          accept="image/*" 
          onChange={handleFileChange}
          style={{ marginBottom: '10px' }}
        />
      </div>
      
      {/* 裁剪区域 */}
      {imageSrc && (
        <div style={{ border: '1px solid #ddd', padding: '10px', marginBottom: '20px' }}>
          <img 
            ref={imageRef} 
            src={imageSrc} 
            alt="待裁剪图片" 
            style={{ maxWidth: '100%', height: 'auto' }}
          />
        </div>
      )}
      
      {/* 操作按钮 */}
      {imageSrc && (
        <div style={{ marginBottom: '20px' }}>
          <button 
            onClick={handleCrop}
            style={{ 
              padding: '8px 16px', 
              background: '#1890ff', 
              color: 'white', 
              border: 'none', 
              borderRadius: '4px', 
              cursor: 'pointer',
              marginRight: '10px'
            }}
          >
            裁剪图片
          </button>
        </div>
      )}
      
      {/* 裁剪结果 */}
      {croppedImage && (
        <div>
          <h3>裁剪结果</h3>
          <div style={{ margin: '10px 0' }}>
            <img 
              src={croppedImage} 
              alt="裁剪后的图片" 
              style={{ maxWidth: '200px', border: '1px solid #ddd' }}
            />
          </div>
          <button 
            onClick={handleDownload}
            style={{ 
              padding: '8px 16px', 
              background: '#52c41a', 
              color: 'white', 
              border: 'none', 
              borderRadius: '4px', 
              cursor: 'pointer'
            }}
          >
            下载图片
          </button>
        </div>
      )}
    </div>
  );
};

export default ImageCropper;
